package icrts.time;
import java.util.SortedSet;
import java.util.TreeSet;

public abstract class AbstractSimulation {
    /**
     * The time variable represents an instant in the timeline of the game world.
     */
    protected double time;
    /**
     * This stores all the events of this particular simulation.
     */
    private SortedSet<Event> diary = new TreeSet<Event>();
    abstract protected boolean stop();

    public abstract class Event implements Comparable {

        public double interval;
	abstract protected void invoke();

        /**
         * Constructor for the event class.
         * @param t the time that this event is created.
         */
        public Event ( double t ) {
            interval = t;
            diary.add(this);
        }
	/**
         * Implements the comparsion functions for this Event object.
         * @param o Object that you compare the Event to
         * @return -1 if this event is eariler than the event you are comparing
         * it to, 0 if they are equal in terms of game time, and 1 if this event
         * is later than the event that is compared.
         * @author Rudolf Lai
         */
        public int compareTo(Object o) {
            Event e = (Event) o;
            return (this.interval<e.interval ? -1 : (this.interval==e.interval ? 0 : 1));
        }

    }

    public void schedule(Event e) {
	diary.add(e);
    }

    public void simulate(){
        while ( !this.stop() && diary.size() > 0 ) {
            Event e   = diary.first();
            diary.remove(e);
            this.time = e.interval;
            if ( !this.stop() ) e.invoke();
	}
    }
}
